<template>
  <el-dialog
    :visible="rangeDialogVisible"
    :before-close="handleClose"
    :close="handleClose"
    :show-close="true"
    :class="{'global-mobile-dialog': showMobilePage}"
    class="small-common-dialog-size range-dialog"
  >
    <Title title="报表数据范围设置" class="title"/>
    <el-form
      ref="rangeForm"
      :rules="rules"
      :model="formData"
      :label-position="showMobilePage?'top':'right'"
      class="form"
      size="small"
      label-width="110px">
      <el-form-item label="报表标题" prop="reportName">
        <el-input v-model="formData.reportName" maxlength="50" class="with240" placeholder="请输入标题，限制50个字" />
      </el-form-item>
      <el-form-item label="订单封账月份" prop="orderSealMonth">
        <el-date-picker
          v-model="formData.orderSealMonth"
          type="monthrange"
          range-separator="至"
          class="with240"
          value-format="timestamp"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          format="yyyy/MM" />
      </el-form-item>
      <el-form-item label="流水到账月份" prop="financeSealMonth">
        <el-date-picker
          v-model="formData.financeSealMonth"
          type="monthrange"
          range-separator="至"
          class="with240"
          value-format="timestamp"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          format="yyyy/MM" />
      </el-form-item>
      <el-form-item label="核销封账月份" prop="writeOffSealMonth">
        <el-date-picker
          v-model="formData.writeOffSealMonth"
          type="monthrange"
          range-separator="至"
          class="with240"
          value-format="timestamp"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          format="yyyy/MM" />
      </el-form-item>
      <el-form-item label="类型" prop="returnType">
        <el-select v-model="formData.returnType" class="with240" placeholder="请选择类型" clearable>
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
            {{ item.label }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="销售" prop="saleId">
        <selectWithoutHttp
          v-model="formData.saleId"
          :remote-method="getMarketList"
          :list-data="marketOption"
          :default-list="defaultList"
          :clearable="true"
          filterable
          remote
          show-check-user
          label-name="value"
          key-name="id"
          class="with240"
          placeholder="请选择销售"
          @change="handelSaleChange"
        />
      </el-form-item>
    </el-form>
    <fixed-pagination :open-fixed="showMobilePage">
      <div class="center">
        <el-button
          :disabled="loading"
          :loading="loading"
          type="primary"
          class="submit-btn"
          size="small"
          @click="handleSubmit"
        >
          确定
        </el-button>
        <el-button
          type="info"
          size="small"
          class="cancel-btn-style"
          @click="handleClose"
        >取消</el-button>
      </div>
    </fixed-pagination>
  </el-dialog>
</template>

<script>
import Title from '@/components/Title';
import { getMarket } from '@/api/select';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import { mapState } from 'vuex';

export default {
  components: {
    Title,
    selectWithoutHttp
  },
  props: {
    isCache: {
      type: Boolean,
      default: false
    },
    isReset: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      rangeDialogVisible: false,
      formData: {
        reportName: '',
        orderSealMonth: '',
        financeSealMonth: '',
        writeOffSealMonth: '',
        returnType: null,
        saleId: '',
        saleName: ''
      },
      typeOptions: [
        { value: 0, label: '欠款分布' },
        { value: 1, label: '到账分布' }
      ],
      marketOption: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    rules() {
      return {
        'reportName': [{ required: true, message: '请输入标题', trigger: 'blur' }],
        'orderSealMonth': [{ required: true, message: '请选择订单封账月份', trigger: 'blur' }],
        'financeSealMonth': [{ required: true, message: '请选择流水到账月份', trigger: 'blur' }],
        'writeOffSealMonth': [{ required: true, message: '请输入核销封账月份', trigger: 'blur' }],
        'returnType': [{ required: true, message: '请选择类型', trigger: 'blur' }]
      };
    },
    defaultList() {
      const saleId = this.formData.saleId;
      const saleName = this.formData.saleName;
      if (saleName && saleId) {
        return [{ id: saleId, value: saleName }];
      }
      return [];
    }
  },
  created() {
    this.getMarketList();
  },
  methods: {
    openDialog() {
      if (this.isCache) {
        const returnParams = localStorage.getItem('returnParams');
        if (returnParams) this.formData = JSON.parse(returnParams);
      }
      if (this.isReset) {
        const returnData = JSON.parse(localStorage.getItem('returnData'));
        const { orderSealMonthStart, orderSealMonthEnd, financeSealMonthStart, financeSealMonthEnd, writeOffSealMonthStart, writeOffSealMonthEnd } = returnData;
        returnData.orderSealMonth = [orderSealMonthStart, orderSealMonthEnd];
        returnData.financeSealMonth = [financeSealMonthStart, financeSealMonthEnd];
        returnData.writeOffSealMonth = [writeOffSealMonthStart, writeOffSealMonthEnd];
        if (returnData) this.formData = returnData;
      }
      this.rangeDialogVisible = true;
    },
    cancelLoading() {
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    handleClose() {
      this.cancelLoading();
      this.$refs['rangeForm'].resetFields();
      this.rangeDialogVisible = false;
    },
    handleSubmit() {
      this.$refs['rangeForm'].validate(valid => {
        if (valid) {
          const { reportName, orderSealMonth, financeSealMonth, writeOffSealMonth, returnType, saleId } = this.formData;
          const params = {
            reportName,
            orderSealMonthStart: orderSealMonth[0],
            orderSealMonthEnd: this.getMonthEnd(orderSealMonth[1]),
            financeSealMonthStart: financeSealMonth[0],
            financeSealMonthEnd: this.getMonthEnd(financeSealMonth[1]),
            writeOffSealMonthStart: writeOffSealMonth[0],
            writeOffSealMonthEnd: this.getMonthEnd(writeOffSealMonth[1]),
            returnType
          };
          if (saleId) params.saleId = saleId;
          this.loading = true;
          if (this.isCache) localStorage.setItem('returnParams', JSON.stringify(this.formData));
          this.$emit('submit', params);
        } else {
          return false;
        }
      });
    },
    getMarketList(params) {
      getMarket(params).then(res => {
        if (res.code === 200 && res.data) {
          this.marketOption = res.data;
        }
      });
    },
    getMonthEnd(time) {
      try {
        // 获取这个月月底
        time = time.toString().length === 10 ? time * 1000 : time;
        const start = new Date(time);
        const nowYear = start.getFullYear(); // 当前年
        const nextMonth = start.getMonth() + 1; // 当前月

        const endDate = new Date(nowYear, nextMonth, 0, '23', '59', '59').valueOf();
        return endDate;
      } catch (error) {
        return time;
      }
    },
    handelSaleChange(data) {
      const item = this.marketOption.find(i => i.id === data);
      if (item) this.formData.saleName = item.value;
    }

  }
};
</script>

<style lang="scss" scoped>
.range-dialog {
  .title {
    margin-bottom: 24px !important;
  }
  &::v-deep {
    .el-dialog {
      // width: 460px !important;
      .el-date-editor {
        .el-range-separator {
          width: 8%;
        }
      }
    }
  }
  .center{
    display: flex;
    justify-content: center;
  }
}
.with240 {
  width: 240px;
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
.global-mobile-dialog {
  .title {
    margin-bottom: 8px !important;
  }
  ::v-deep {
    .el-form-item__label {
      padding: 0 !important;
    }
    .el-dialog__body {
      margin-bottom: 56px !important;
      max-height: 80vh;
      overflow-y: auto;
    }
  }
}
</style>
